﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using log4net;
using MaximServices.Common;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Impl;

namespace MaximJob
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var startup = new Startup();
            var serviceCollection = new ServiceCollection();

            startup.ConfigureServices(serviceCollection);

            //运行计划任务 test
            await RunTaskScheduler().ConfigureAwait(false);

            Console.Read();
        }

        private static async Task RunTaskScheduler()
        {
            try
            {
                var logRepository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
                log4net.Config.XmlConfigurator.Configure(logRepository, new System.IO.FileInfo("log4net.config"));

                await Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error running example: " + ex.Message);
                Console.WriteLine(ex.ToString());
            }
        }

        private static async Task Run()
        {
            ILog log = LogManager.GetLogger(typeof(Program));

            log.Info("------- Initializing ----------------------");

            var jobConfigPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "quartz_jobs.xml");

            // First we must get a reference to a scheduler
            var properties = new NameValueCollection
            {
                ["quartz.scheduler.instanceName"] = "XmlConfiguredInstance",
                ["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz",
                ["quartz.threadPool.threadCount"] = "5",
                ["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins",
                ["quartz.plugin.xml.fileNames"] = jobConfigPath,
                // this is the default
                ["quartz.plugin.xml.FailOnFileNotFound"] = "true",
                // this is not the default
                ["quartz.plugin.xml.failOnSchedulingError"] = "true"
            };

            // set thread pool info

            // job initialization plugin handles our xml reading, without it defaults are used

            ISchedulerFactory sf = new StdSchedulerFactory(properties);
            IScheduler sched = await sf.GetScheduler();

            // we need to add calendars manually, lets create a silly sample calendar
            //var dailyCalendar = new DailyCalendar("00:01", "23:59");
            //dailyCalendar.InvertTimeRange = true;
            //await sched.AddCalendar("cal1", dailyCalendar, false, false);

            log.Info("------- Initialization Complete -----------");

            // all jobs and triggers are now in scheduler

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();
            // wait long enough so that the scheduler as an opportunity to
            // fire the triggers
            //log.Info("------- Waiting 10 seconds... -------------");

            //await Task.Delay(10 * 1000);
            //Console.WriteLine("press any key to exit...");

            // shut down the scheduler
            //log.Info("------- Shutting Down ---------------------");
            //await sched.Shutdown(true);
            //log.Info("------- Shutdown Complete -----------------");
        }
    }
}
